<script setup>
import { onMounted, ref } from 'vue'
import Card from '@/views/new-screen/components/card.vue'
import DrawEcharts from '@/components/draw-echarts.vue'
import icon_house from '@/assets/imgs/bt_sy.png'
import {
  getRealtyProjectOverview,
  getRankingByType,
} from '../api.js'
import DotsTabs from '@/views/new-screen/components/dotsTabs.vue'

const props = defineProps({
  isExpanded: Boolean,
  activeName: String,
})

const getChartPieOption = ({ list, image }) => {
  const total = list.reduce((a, b) => a + b.value, 0)
  const colors = ['#00FFA0', '#1FF0EF', '#FADD8D']
  return {
    color: colors,
    tooltip: {
      trigger: 'item',
      formatter: '{b} <br/> {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: '45%',
      top: 'middle',
      data: list.map(item => item.name),
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 10,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: (name) => {
        const item = list.find(item => item.name === name)
        const value = item.value
        const percent = (value / total * 100).toFixed(2)
        // 使用富文本格式，每部分独立控制样式
        return `{name|${name}}{value|${value}}{percent|${percent}%}`
      },
      textStyle: {
        rich: {
          name: {
            color: '#e0e0e0',    // 名称颜色
            fontSize: 13,        // 名称字号
            fontWeight: 'normal',
            padding: [0, 10, 0, 0] // 右边距
          },
          value: {
            color: (params) => {
              // 根据索引获取对应颜色
              const index = list.findIndex(item => item.name === params.name)
              console.log('idx ', index)
              return colors[index % colors.length] || '#ffffff'
            },
            fontSize: 15,        // 数值字号
            fontWeight: 'bold',
            padding: [0, 5, 0, 0]  // 右边距
          },
          percent: {
            color: (params) => {
              // 根据索引获取对应颜色
              const index = list.findIndex(item => item.name === params.name)
              return colors[index % colors.length] || '#00dfff'
            },
            fontSize: 12,        // 百分比字号
            fontWeight: 'normal'
          }
        }
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        center: ['15%', '50%'],
        radius: ['53%', '70%'],
        padAngle: 3, // 轻微的角度间隙
        labelLine: {
          length: 10
        },
        inverse: true,
        label: {
          show: false,
          formatter: '{b|{b}}\n{hr|}\n{c|{c}} {unit|户}  {per|{d}%}  ',
          // backgroundColor: '#F6F8FC',
          // borderColor: '#8C8D8E',
          // borderWidth: 1,
          // borderRadius: 4,
          rich: {
            b: {
              color: '#ffffff',
              fontSize: 14,
            },
            hr: {
              borderColor: '#8C8D8E',
              width: '100%',
              borderWidth: 1,
              height: 0
            },
            c: {
              color: '#ffffff',
              fontSize: 14,
              lineHeight: 28
            },
            unit: {
              color: '#ccc',
              fontWeight: 'normal',
            },
            per: {
              color: '#ffffff',
              lineHeight: 28
              // backgroundColor: '#4C5058',
              // padding: [3, 4],
              // borderRadius: 4
            }
          }
        },
        data: list,
      }
    ],
    backgroundColor: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [{
          offset: 0, color: '#01153c21' // 0% 处的颜色
      }, {
          offset: 1, color: '#01153c89' // 100% 处的颜色
      }],
      global: false // 缺省为 false
    },
    // 添加 graphic 组件显示图片
    graphic: {
      elements: [{
        type: 'image',
        key: 'centerImage',
        z: 100,
        style: {
          image: image, // 你的图片路径
          width: 90,
          height: 90
        },
        left: '4%',
        top: 'center'
      }]
    },
  }
}

const propertyItemOverview = ref([
  {
    name: '小区总数',
    value: '1658'
  },
  {
    name: '物业总数',
    value: '5698'
  },
  {
    name: '项目总数',
    value: '2368'
  },
  {
    name: '服务中项目总数',
    value: '2368'
  },
])

const propertyItemChartPieRef = ref(null)
const updateChartPiePropertyItem = (pieList = []) => {
  propertyItemChartPieRef.value?.updateOption(getChartPieOption({ list: pieList, image: icon_house }))
}

const updateDataOverview = (data) => {
  data.type.forEach((item) => {
    const one = propertyItemOverview.value.find((e) => e.name === item.type)
    if (one) { 
      one.value = item.count
    }
  })

  const pieList = data?.charts?.map((e) => ({ name: e.type, value: e.count }))
  if (pieList) {
    updateChartPiePropertyItem(pieList)
  }
}

const getChartBarOption = (data) => {
  return {
    xAxis: {
      // max: 'dataMax',
      show: true,
    },
    grid: {
      top: '3%',
      left: '6%',
      right: '8%',
      bottom: '3%',
      containLabel: true
    },
    yAxis: {
      type: 'category',
      data: data.yAxis,
      inverse: true,
      axisLabel: {
        color: '#fff'
      },
      animationDuration: 300,
      animationDurationUpdate: 300,
      // max: 2 // only the largest 3 bars will be displayed
    },
    tooltip: {
      show: true,
    },
    series: [
      {
        realtimeSort: true,
        name: '分城区统计',
        type: 'bar',
        barWidth: 10,
        data: data.data,
        showBackground: true,
        label: {
          show: true,
          position: 'right',
          valueAnimation: true
        },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 1,
            colorStops: [{
                offset: 0, color: '#0076FF' // 0% 处的颜色
            }, {
                offset: 1, color: '#0DD6EE' // 100% 处的颜色
            }],
            global: false // 缺省为 false
          },
        },
      }
    ],
    legend: {
      show: false
    },
    backgroundColor: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [{
          offset: 0, color: '#01153c21' // 0% 处的颜色
      }, {
          offset: 1, color: '#01153c89' // 100% 处的颜色
      }],
      global: false // 缺省为 false
    },
    // animationDuration: 0,
    // animationDurationUpdate: 3000,
    // animationEasing: 'linear',
    // animationEasingUpdate: 'linear'
  }
}


const districtTotalChartBarRef = ref(null)

const updateDataTotalByDistrict = (res) => {
  const data = {
    yAxis: res.cityNames,
    data: res[activeName.value.slice(1)]
  }
  districtTotalChartBarRef.value?.updateOption(getChartBarOption(data))
}

const reqRankingData = () => {
  getRankingByType({ type: activeName.value.slice(1) })
    .then(res => {
      updateDataTotalByDistrict(res.data)
    })
}
const activeName = ref('按小区')
const tabList = ref([
  { name: '按小区' },
  { name: '按项目' },
  { name: '按服务中项目' },
])
const onChangeTab = (name) => {
  activeName.value = name
  reqRankingData()
}

const reqData = () => {
  onChangeTab('按小区')
  getRealtyProjectOverview()
    .then((overview) => {
      if (overview.success) {
        updateDataOverview(overview.data)
      }
    })
}

onMounted(() => {
  reqData()
})
</script>

<template>
  <div :class="['left', isExpanded ? 'active' : '']">
    <card name="物业项目" class="property-item-card">
      <div class="section">
        <div class="section-title">＞ 物业项目信息</div>
        <div class="overview-wrap">
          <div class="overview-box" v-for="item in propertyItemOverview" :key="item.name">
            {{ item.name }}
            <span class="overview-value">{{ item.value }}</span>
          </div>
        </div>
        <div class="chart">
          <draw-echarts
            ref="propertyItemChartPieRef"
            width="420"
            height="140"
            :options="{}"
          ></draw-echarts>
        </div>
      </div>
      <div class="section">
        <div class="section-title">＞ 分城区统计</div>
        <DotsTabs :tab-list="tabList" v-model:activeName="activeName" @change="onChangeTab" />
        <div class="chart">
          <draw-echarts
            ref="districtTotalChartBarRef"
            width="420"
            height="520"
            :options="{}"
          ></draw-echarts>
        </div>
      </div>
    </card>
  </div>
</template>

<style scoped lang="scss">
.left {
  .title-icon {
    display: inline-flex;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 61px;
    position: relative;
    bottom: 20px;
    // margin-top: 10px;
  }

  .property-item-card {
    height: 100%;

    .section-title {
      line-height: 30px;
      font-size: 16px;
      font-weight: bold;
      color: #fff;
      margin-bottom: 10px;
    }

    .overview-wrap {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-bottom: 10px;

      .overview-box {
        position: relative;
        margin-bottom: 5px;
        padding-left: 16px;
        width: 46%;
        height: 40px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        gap: 5px;
      
        text-align: left;
        color: #eee;

        background: linear-gradient(to right, #044e79 0%, #063254 50%, #081a3400 100%);
        border: solid 1px;
        border-image: linear-gradient(90deg, #00EDF4, #081731) 1;
        .overview-value {
          position: relative;
          font-size: 20px;
          font-weight: bold;
          color: #fff;
        }
      }
    }

  }

  .my-tabs {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #bbdbf6;
    height: 32px;
    line-height: 32px;
    margin-bottom: 10px;

    .dots {
      display: flex;
      align-items: center;
      gap: 5px;
      i {
        display: inline-block;
        width: 3px;
        height: 3px;
        border-radius: 3px;
        background: #bbdbf6;
      }
    }

    .tabs {
      display: flex;
    }

    .tab-item {
      position: relative;
      cursor: pointer;
      padding: 0 6px;
      margin: 0 6px;
      font-size: 13px;
    }
    .tab-item::before {
      content: '';
      position: absolute;
      width: 2px;
      height: 0.7em;
      right: -7px;
      top: 12px;
      background-color: #ffffff;
    }
    .tab-item:last-child::before {
      display: none;
    }
    .tab-item.on {
      color: #f8ea9a;
    }
    .tab-item.on::after {
      content: '';
      display: block;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg,rgba(248, 234, 154, 0.01), rgba(248, 234, 154, 0.4), rgba(248, 234, 154, 0.01));
    }
  }
}
</style>
